﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Media;
using System.Threading;
using System.Linq;

using System.Windows.Controls.Primitives;
namespace BootyShaker
{
    public enum CurrentView
    {
        MainMenu,
        SettingsScreen,
        AboutScreen,
        HelpScreen,
        ShakeDesigner,
        GameScreen
    }
    public class TiltableControl : Grid
    {
    } 
    public partial class MainPage : PhoneApplicationPage
    {
        private PhotoChooserTask photoChooserTask;
        private CameraCaptureTask cameraCaptureTask;

        Action ChildGoBackMethod;
        SettingsScreen _settingsMenu;
        SettingsScreen settingsMenu
        {
            get
            {
                if (_settingsMenu == null)
                {
                    _settingsMenu = new SettingsScreen(BackToMainMenu);
                    _settingsMenu.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    PagePlaceholder.Children.Add(_settingsMenu);

                    //addLayer(optionsMenu, CurrentView.OptionsMenu);

                }
                return _settingsMenu;
            }
        }
        AboutPage _aboutPage;
        AboutPage aboutPage
        {
            get
            {
                if (_aboutPage == null)
                {
                    _aboutPage = new AboutPage(BackToMainMenu);
                    _aboutPage.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    MenuPlaceholder.Children.Add(_aboutPage);

                    //addLayer(optionsMenu, CurrentView.OptionsMenu);

                }
                return _aboutPage;
            }
        }

        HelpPage _helpPage;
        HelpPage helpPage
        {
            get
            {
                if (_helpPage == null)
                {
                    _helpPage = new HelpPage(BackToMainMenu);
                    _helpPage.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    MenuPlaceholder.Children.Add(_helpPage);

                    //addLayer(optionsMenu, CurrentView.OptionsMenu);

                }
                return _helpPage;
            }
        }

        ShakeDesigner _shakeDesigner;
        ShakeDesigner shakeDesigner
        {
            get
            {
                if (_shakeDesigner == null)
                {
                    _shakeDesigner = new ShakeDesigner(BackToMainMenu);
                    _shakeDesigner.LayoutRoot.Visibility = System.Windows.Visibility.Collapsed;

                    PagePlaceholder.Children.Add(_shakeDesigner);

                    //addLayer(optionsMenu, CurrentView.OptionsMenu);

                }
                return _shakeDesigner;
            }
        }
        GameScreen _gameScreen;
        GameScreen gameScreen
        {
            get
            {
                if (_gameScreen == null)
                {
                    _gameScreen = new GameScreen(BackToShakeDesigner);
                    _gameScreen.Visibility = System.Windows.Visibility.Collapsed;

                    PagePlaceholder.Children.Add(_gameScreen);

                    //addLayer(optionsMenu, CurrentView.OptionsMenu);

                }
                return _gameScreen;
            }
        }
        private void BackToMainMenu()
        {
            if (App.currentView == CurrentView.ShakeDesigner)
            {
                ShowMainPageBegin();
                this.ApplicationBar = null;
                App.currentView = CurrentView.MainMenu;
                return;
            }
            ShowMainMenuBegin();
            App.currentView = CurrentView.MainMenu;
            this.ApplicationBar = null;
            ChildGoBackMethod = null;
        }
        private void BackToShakeDesigner()
        {
           
            MainPageContent.Visibility = Visibility.Visible;
            MainMenu.Visibility = System.Windows.Visibility.Visible;
            this.ApplicationBar = shakeDesigner.ApplicationBar;
            ChildGoBackMethod = shakeDesigner.GoBack;
            if (App.currentView == CurrentView.GameScreen)
            {
                gameScreen.Visibility = Visibility.Collapsed;
                gameScreen.OnNavigatedFrom();
                shakeDesigner.Visibility = Visibility.Visible;
                shakeDesigner.OnNavigatedTo();
            }
            else
            {
                shakeDesigner.Show.Begin();
            }

            App.currentView = CurrentView.ShakeDesigner;
        }
        // Constructor

        private void GoToScreen(CurrentView cw)
        {
            switch (cw)
            {
                case CurrentView.AboutScreen:
                    break;
                case CurrentView.HelpScreen:

                    if (App.currentView == CurrentView.ShakeDesigner)
                    {

                        MainPageContent.Visibility = Visibility.Visible;
                        MainMenu.Visibility = System.Windows.Visibility.Collapsed;
                        shakeDesigner.Hide.Begin();
                        ShowMainPageBegin();
                        ChildGoBackMethod = helpPage.GoBack;
                        helpPage.ShowPage(BackToShakeDesigner);
                        this.ApplicationBar = null;
                    }
                    else
                    {
                        //var tohide = PagePlaceholder.Children;
                        //foreach (UIElement el in tohide)
                        //{
                        //    el.Visibility = System.Windows.Visibility.Collapsed;
                        //}
                        //helpPage.ShowPage(BackToMainMenu);
                    }
                    App.currentView = CurrentView.HelpScreen;
                    break;
                case CurrentView.MainMenu:
                    break;
                case CurrentView.SettingsScreen:
                    if (App.currentView == CurrentView.ShakeDesigner)
                    {
                        MainPageContent.Visibility = Visibility.Collapsed;
                        MainMenu.Visibility = System.Windows.Visibility.Collapsed;
                        shakeDesigner.Hide.Begin();
                        settingsMenu.ShowPage(BackToShakeDesigner);
                        ChildGoBackMethod = settingsMenu.GoBack;
                        App.currentView = CurrentView.SettingsScreen;
                        this.ApplicationBar = settingsMenu.ApplicationBar;
                    }
                    break;
                case CurrentView.ShakeDesigner:
                    break;
                case CurrentView.GameScreen:

                    ChildGoBackMethod = BackToShakeDesigner;
                    shakeDesigner.Visibility = Visibility.Collapsed;
                    shakeDesigner.OnNavigatedFrom();
                    gameScreen.Visibility = Visibility.Visible;
                    ApplicationBar = null;
                    App.currentView = CurrentView.GameScreen;
                    gameScreen.OnNavigatedTo();
                    
                   
                    break;

            }

        }
        public MainPage()
        {
            InitializeComponent();
            photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed +=
            new EventHandler<PhotoResult>(PhotoChooserTaskCompleted);
            cameraCaptureTask = new CameraCaptureTask();
            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCapture_Completed);
            App.NavigateTo = GoToScreen;

            TiltEffect.TiltableItems.Add(typeof(TiltableControl)); 

            App.shakeObjects = new List<ShakeObjectCtl>();
            if (App.IsTrial)
            {
                AdDuplex.IsEnabled = true;
                AdDuplex.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                AdDuplex.IsEnabled = false;
                AdDuplex.Visibility = System.Windows.Visibility.Collapsed;
            }

        }
        void AdRotatorControl_Log(string message)
        {
            Debug.WriteLine(message);
        }

        void cameraCapture_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(e.ChosenPhoto);
                WriteableBitmap picLibraryImage = new WriteableBitmap(bitmap);
                App.currentShaker = new Shaker();
                App.currentShaker.shakeImage = picLibraryImage;

                //Dispatcher.BeginInvoke(() =>
                //{
                //    this.NavigationService.Navigate(new Uri("/ShakeDesigner.xaml", UriKind.Relative));
                //});
                ShowShakeDesigner();
            }
        }

        private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(e.ChosenPhoto);
                WriteableBitmap picLibraryImage = new WriteableBitmap(bitmap);
                App.currentShaker = new Shaker();
                App.currentShaker.shakeImage = picLibraryImage;

                //Dispatcher.BeginInvoke(() =>
                //{
                //    this.NavigationService.Navigate(new Uri("/ShakeDesigner.xaml", UriKind.Relative));
                //});
                ShowShakeDesigner();
            }

        }
        List<HubTile> HtList = new List<HubTile>();
        //private void LoadFilesThread()
        //{


        //    if (App.IsExit) return;

        //    CopySamples();

        //    Dispatcher.BeginInvoke(() =>
        //   {
        //       overlayLoading.Visibility = System.Windows.Visibility.Visible;
        //       TileGrid.Visibility = System.Windows.Visibility.Collapsed;
        //   });
        //    string[] files;
        //    using (IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication())
        //    {
        //        files = myStore.GetFileNames("*.shk");
        //    }
        //    Dispatcher.BeginInvoke(() =>
        //    {
        //        TileGrid.RowDefinitions.Clear();
        //        TileGrid.Children.Clear();
        //        HtList.Clear();
        //    });

        //    foreach (string file in files)
        //    {

        //        try
        //        {
        //            Shaker.GetPreviewImage(file);
        //        }
        //        catch (Exception ex)
        //        {
        //            // myStore.DeleteFile(file);
        //        }



        //    }
        //    Dispatcher.BeginInvoke(() =>
        //    {
        //        int col = 0;
        //        int row = -1;

        //        foreach (string file in files)
        //        {
        //            try
        //            {

        //                BitmapImage bi = new BitmapImage();
        //                bi.CreateOptions = BitmapCreateOptions.BackgroundCreation;
        //                bi.ImageOpened += new EventHandler<RoutedEventArgs>(bmp_ImageOpened);
        //                bi.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(bmp_ImageFailed);

        //                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        //                {

        //                    using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(App.thumbPath + "\\" + Path.GetFileNameWithoutExtension(file) + ".jpg", FileMode.Open, FileAccess.Read))
        //                    {
        //                        bi.SetSource(fileStream);

        //                    }
        //                }


        //                if (col % 2 == 0)
        //                {

        //                    RowDefinition rd = new RowDefinition();
        //                    TileGrid.RowDefinitions.Add(rd);

        //                    col = 0;
        //                    row++;
        //                }

        //                HubTile ht = new HubTile();
        //                ht.Title = Path.GetFileNameWithoutExtension(file);

        //                ht.Margin = CameraTile.Margin;
        //                ht.Background = CameraTile.Background;
        //                ht.GroupTag = CameraTile.GroupTag;

        //                //Shaker.GetPreviewImage(file);


        //                ht.Source = bi;
        //                ht.UpdateLayout();



        //                ht.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(ht_Tap);
        //                ht.Tag = file;
        //                ht.FontSize = 10;
        //                ht.FontStretch = FontStretches.UltraCondensed;
        //                HtList.Add(ht);
        //                AddContextMenuWithMenuItems(ht);

        //                TileGrid.Children.Add(ht);
        //                Grid.SetColumn(ht, col);
        //                Grid.SetRow(ht, row);
        //                col++;


        //            }
        //            catch (Exception ex)
        //            {
        //                // myStore.DeleteFile(file);
        //            }

        //        }

        //        overlayLoading.Visibility = System.Windows.Visibility.Collapsed;
        //        TileGrid.Visibility = System.Windows.Visibility.Visible;
        //    });
        //    App.LoadNeeded = false;

        //}
        public class TileData : INotifyPropertyChanged
        {

            private string _fileName;
            public string FileName
            {
                get
                {
                    return _fileName;
                }
                set
                {
                    _fileName = value;
                    NotifyPropertyChanged("FileName");
                }
            }
            private string _projectName;
            public string ProjectName
            {
                get
                {
                    return _projectName;
                }
                set
                {
                    _projectName = value;
                    NotifyPropertyChanged("ProjectName");
                }
            }
            private ImageSource _imageSource;
            public ImageSource ImageSource
            {
                get
                {
                    return _imageSource;
                }
                set
                {
                    _imageSource = value;
                    NotifyPropertyChanged("ImageSource");
                }
            }
            public int index { get; set; }
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged(String propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }


        ObservableCollection<TileData> PicturesList;
        public static bool picturesLoaded = false;

        private void LoadProjects()
        {

            if (App.IsExit) return;

            CopySamples();

            if (!App.LoadNeeded)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    lbTiles.Visibility = System.Windows.Visibility.Visible;

                });
                return;
            }

            PicturesList = new ObservableCollection<TileData>();
            Dispatcher.BeginInvoke(() =>
            {
                lbTiles.Visibility = System.Windows.Visibility.Visible;
                TilesLoadingBar.Visibility = System.Windows.Visibility.Visible;
                txtNoItems.Visibility = System.Windows.Visibility.Collapsed;
                TilesProgressTransform.ScaleX = 0;
                lbTiles.ItemsSource = PicturesList;
                
            });


            string[] files;
            using (IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                files = myStore.GetFileNames("*.shk");
            }

            int cnt = files.Length;
            WriteableBitmap[] bmp = new WriteableBitmap[cnt];
            bool bitmapsCreated = false;
            Dispatcher.BeginInvoke(() =>
            {
                lock (bmp)
                {

                    for (int i = 0; i != (bmp.Length); i++)
                    {
                        if (backgroundWorker.CancellationPending) return;
                        bmp[i] = new WriteableBitmap(180, 180);
                    }
                    bitmapsCreated = true;
                }
            });


            foreach (string file in files)
            {

                try
                {
                    Shaker.GetPreviewImage(file);
                }
                catch (Exception ex)
                {
                    // myStore.DeleteFile(file);
                }



            }
            while (!bitmapsCreated)
            {
                Thread.Sleep(100);
            }
            if (backgroundWorker.CancellationPending) return;
            lock (bmp)
            {

                //foreach (var tst in test)
                //{

                //    ImageData item = new ImageData();
                //    var img = tst;
                //    Stream src = tst.GetThumbnail();
                //    bmp[index].LoadJpeg(src);
                //    src.Dispose();

                //    item.ImageSource = bmp[index];
                //    //item.ImageSource = bmp;
                //    // LoadThumbAsync(item, img.GetThumbnail(), bmp, this);

                //    item.hashcode = img.GetHashCode();
                //    item.Include = App.collection.PicturesCollection.ContainsKey(item.hashcode) ? Visibility.Visible : Visibility.Collapsed;
                //    item.index = picturelist.IndexOf(img);




                //}

                int index = 0;
                foreach (string file in files)
                {
                    try
                    {
                        if (backgroundWorker.CancellationPending) return;

                        //BitmapImage bi = new BitmapImage();
                        //bi.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                        //bi.ImageOpened += new EventHandler<RoutedEventArgs>(bmp_ImageOpened);
                        //bi.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(bmp_ImageFailed);

                        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {

                            using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(App.thumbPath + "\\" + Path.GetFileNameWithoutExtension(file) + ".jpg", FileMode.Open, FileAccess.Read))
                            {
                                bmp[index].LoadJpeg(fileStream);
                                fileStream.Dispose();
                                //bi.SetSource(fileStream);

                            }
                        }

                        //Stream src = tst.GetThumbnail();
                        //bmp[index].LoadJpeg(src);
                        //src.Dispose();f

                        TileData td = new TileData();
                        

                        td.ProjectName = Path.GetFileNameWithoutExtension(file);

                        td.ImageSource = bmp[index];

                        td.FileName = file;


                        //AddContextMenuWithMenuItems(ht);
                        index++;

                        Dispatcher.BeginInvoke(() =>
                        {
                            TilesProgressTransform.ScaleX = (double)index / files.Length;
                            PicturesList.Add(td);
                        });
                    }
                    catch (Exception ex)
                    {
                        // myStore.DeleteFile(file);
                    }
                }

            }

            picturesLoaded = true;
            Dispatcher.BeginInvoke(() =>
            {
                TilesLoadingBar.Visibility = System.Windows.Visibility.Collapsed;
              
                if (PicturesList.Count == 0)
                {
                    txtNoItems.Visibility = System.Windows.Visibility.Visible;
                }
                else 
                {
                    txtNoItems.Visibility = System.Windows.Visibility.Collapsed;
                }
            });
            App.LoadNeeded = false;
        }

        void bmp_ImageOpened(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("opened");
        }

        void bmp_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Debug.WriteLine(e.ErrorException.Message);
        }

        private void LoadFiles()
        {
            if (!App.LoadNeeded) return;
            //System.Threading.Thread startupThread = new System.Threading.Thread(new System.Threading.ThreadStart(LoadFilesThread));
            //startupThread.Start();

            if (backgroundWorker != null && backgroundWorker.IsBusy)
            {
                backgroundWorker.CancelAsync();

                TilesLoadingBar.Visibility = System.Windows.Visibility.Collapsed;
            }
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.WorkerSupportsCancellation = true;
            backgroundWorker.DoWork +=
                (s, e) =>
                {

                    // runs on background thread

                    //Dispatcher.BeginInvoke(() =>
                    //{
                    //    lbTiles.Visibility = System.Windows.Visibility.Collapsed;
                    //});
                    LoadProjects();


                };


            backgroundWorker.RunWorkerAsync();


            //System.Threading.Thread t = new System.Threading.Thread(LoadFilesThread);
            //t.Start();

        }
        BackgroundWorker backgroundWorker;

        private void CopySamples()
        {
            lock (App.operationSyncLock)
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("AppLaunchCount"))
                {
                    var count = (int)IsolatedStorageSettings.ApplicationSettings["AppLaunchCount"];
                    count++;
                    IsolatedStorageSettings.ApplicationSettings["AppLaunchCount"] = count;
                }
                else
                {
                    try
                    {
                        //Utils.Util.CopyFromContentToStorage("files/Sample1.shk");
                        //Utils.Util.CopyFromContentToStorage("files/Sample2.shk");
                        // Utils.Utils.CopyFromContentToStorage("files/keira.shk");
                    
                        //Utils.Util.CopyFromContentToStorage("files/untitled000.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled001.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled002.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled003.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled004.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled005.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled006.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled007.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled008.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled009.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled010.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled011.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled012.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled013.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled014.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled015.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled016.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled017.shk");

                    }
                    catch { }

                    IsolatedStorageSettings.ApplicationSettings.Add("AppLaunchCount", 0);
                    //string[] files = System.IO.Directory.GetFileNames("*.shk");
                }
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }
        ContextMenu contextMenu;
        //private void AddContextMenuWithMenuItems(HubTile ht)
        //{
        //    contextMenu = new ContextMenu();
        //    MenuItem menuItemDelete = new MenuItem() { Header = "Delete", Tag = "Delete" };
        //    menuItemDelete.Click += new RoutedEventHandler(menuItemDelete_Click);
        //    contextMenu.Items.Add(menuItemDelete);
        //    menuItemDelete.Tag = ht;
        //    ContextMenuService.SetContextMenu(ht, contextMenu);

        //}

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            if (App.IsTrial)
            {
                btnBuy.Visibility = System.Windows.Visibility.Visible;
                txtBuy.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                btnBuy.Visibility = System.Windows.Visibility.Collapsed;
                txtBuy.Visibility = System.Windows.Visibility.Collapsed;
            }

            //Dispatcher.BeginInvoke(() =>
            //{

            if (App.IsTrial)
            {
                AdDuplex.IsEnabled = true;
                AdDuplex.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                AdDuplex.IsEnabled = false;
                AdDuplex.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (App.currentView == null)
            {
                App.currentView = CurrentView.MainMenu;
            }
            switch (App.currentView)
            {
                case CurrentView.AboutScreen:

                    break;
                case CurrentView.HelpScreen:

                    break;
                case CurrentView.MainMenu:
                    LoadFiles();
                    UnFreezeHubTiles();
                    break;
                case CurrentView.SettingsScreen:

                    break;
                case CurrentView.ShakeDesigner:
                    shakeDesigner.OnNavigatedTo();
                    break;
            }
            //});
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (App.IsTrial)
            {
                AdDuplex.IsEnabled = true;
                AdDuplex.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                AdDuplex.IsEnabled = false;
                AdDuplex.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void FreezeHubTiles()
        {
            if (!CameraTile.IsFrozen) CameraTile.IsFrozen = true;
            if (!GalleryTile.IsFrozen) CameraTile.IsFrozen = true;
            foreach (HubTile ht in HtList)
            {
                if (!ht.IsFrozen) ht.IsFrozen = true;
            }
        }
        private void UnFreezeHubTiles()
        {
            if (CameraTile.IsFrozen) CameraTile.IsFrozen = false;
            if (GalleryTile.IsFrozen) CameraTile.IsFrozen = false;
            foreach (HubTile ht in HtList)
            {
                if (ht.IsFrozen) ht.IsFrozen = false;
            }
        }
        private void OpenCamera(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            cameraCaptureTask.Show();

        }

        private void OpenGallery(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            photoChooserTask.Show();
        }
        private void ht_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            
            showProgresBar();
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            try
            {
                App.currentShaker = Shaker.Load((string)((HubTile)sender).Tag);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Oops, something went wrong! I'm not sure I can handle this one.", "Sorry, Mike", MessageBoxButton.OK);
                //var myStore = IsolatedStorageFile.GetUserStoreForApplication();
                //myStore.DeleteFile((string)((HubTile)sender).Tag);
                hideProgresBar();
                UnFreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
                return;
            }
            hideProgresBar();

            ShowShakeDesigner();
            //Dispatcher.BeginInvoke(() =>
            //{
            //    this.NavigationService.Navigate(new Uri("/ShakeDesigner.xaml", UriKind.Relative));
            //});
        }

        private void ShowShakeDesigner()
        {

            HideMainPageBegin();
            shakeDesigner.doLoad = true;
            shakeDesigner.Show.Begin();
            this.ApplicationBar = shakeDesigner.ApplicationBar;
            ChildGoBackMethod = shakeDesigner.GoBack;
            App.currentView = CurrentView.ShakeDesigner;
        }

        void showProgresBar() { progressBar.Visibility = System.Windows.Visibility.Visible; }
        void hideProgresBar() { progressBar.Visibility = System.Windows.Visibility.Collapsed; }
        private void menuItemDelete_Click(object sender, RoutedEventArgs e)
        {
            showProgresBar();
            var myStore = IsolatedStorageFile.GetUserStoreForApplication();
           // HubTile ht = (HubTile)((MenuItem)sender).Tag;
            var menuItem = (MenuItem)sender;
            var tile = menuItem.DataContext as TileData;
            //HubTile ht = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget
            //                                               as HubTile);
            myStore.DeleteFile(tile.FileName);
            App.LoadNeeded = true;
            LoadFiles();
            hideProgresBar();

        }


        private void btnRate_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();
        }

        private void btnBuy_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            //Show an application, using the default ContentType.
            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.Show();
        }

        private void btnAbout_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");

            //Dispatcher.BeginInvoke(() =>
            //{
            //    //this.NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
            //    this.NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
            //});
            ShowAboutPage();
        }
        private void HideMainMenuBegin()
        {
            MainMenu.IsHitTestVisible = false;
            HideMainMenu.Begin();
        }
        private void ShowMainMenuBegin()
        {
            MainMenu.IsHitTestVisible = true;
            ShowMainMenu.Begin();
        }
        private void HideMainPageBegin()
        {
            MainPageContent.IsHitTestVisible = false;
            HideMainPage.Begin();
        }
        private void ShowMainPageBegin()
        {
            MainPageContent.IsHitTestVisible = true;
            ShowMainPage.Begin();
        }
        private void ShowAboutPage()
        {
            HideMainMenuBegin();
            aboutPage.Show.Begin();
            ChildGoBackMethod = aboutPage.GoBack;
            App.currentView = CurrentView.AboutScreen;
        }
        private void btnFacebook_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webbrowser = new WebBrowserTask();
            webbrowser.Uri = new Uri("http://www.facebook.com/VincentsBootyShaker");
            webbrowser.Show();
        }

        private void imgHelp_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");

            //Dispatcher.BeginInvoke(() =>
            //{
            //    //this.NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
            //    this.NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
            //});
            ShowHelpPage();
        }
        private void ShowHelpPage()
        {
            HideMainMenuBegin();
            //helpPage.Show.Begin();
            helpPage.ShowPage(BackToMainMenu);
            ChildGoBackMethod = helpPage.GoBack;
            App.currentView = CurrentView.HelpScreen;
        }
        private void ShowMainPage_Completed(object sender, EventArgs e)
        {
            LoadFiles();
            UnFreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
        }

        private void ShowMainMenu_Completed(object sender, EventArgs e)
        {
            ShowMainPage_Completed(sender, e);
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (App.currentView == CurrentView.ShakeDesigner)
            {
                shakeDesigner.OnBackKeyPress(e);
            }
            else if (App.currentView == CurrentView.MainMenu)
            {

            }
            else
            {
                ChildGoBackMethod();
                // ShowMainMenuBegin();
                e.Cancel = true;
            }
            //if (popup != null && popup.IsOpen)
            //{
            //    saveCallback("", true);
            //    e.Cancel = true;
            //}
        }

    }
}
